<template>
  <div class="new-retreat route-page">
    <section class="content">
      <!-- <a-row :gutter="12">
        <a-col :span="12" class="mt-10">
          <a-card size="small" title="退租信息">
            <a-form layout="vertical">
              <a-row :gutter="12">
                <a-col :span="12">
                  <a-form-item
                    label="退租类型"
                    v-bind="validateInfos.retreatType"
                  >
                    <a-select v-model:value="modelRef.retreatType" disabled>
                      <a-select-option value="5">变更退租</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    label="退租日期"
                    v-bind="validateInfos.retreatDate"
                  >
                    <a-date-picker
                      v-model:value="modelRef.retreatDate"
                      format="YYYY-MM-DD"
                      placeholder=""
                      :open="endOpen"
                      @openChange="handleRetreatDateOpenChange"
                      @change="handleRetreatDateChange"
                      style="width: 100%"
                      disabled
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="12">
                <a-col :span="12">
                  <a-form-item
                    label="工商注册地址变更日期"
                    v-bind="validateInfos.addressChangeDate"
                  >
                    <a-date-picker
                      v-model:value="modelRef.addressChangeDate"
                      type="date"
                      placeholder=""
                      style="width: 100%"
                      disabled
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    label="协议签订日期"
                    v-bind="validateInfos.signDate"
                  >
                    <a-date-picker
                      v-model:value="modelRef.signDate"
                      :disabled-date="disabledStartDate"
                      format="YYYY-MM-DD"
                      placeholder=""
                      style="width: 100%"
                      disabled
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="12">
                <a-col :span="12">
                  <a-form-item
                    label="退租原因"
                    v-bind="validateInfos.retreatReason"
                  >
                    <a-select
                      v-model:value="modelRef.retreatReason"
                      placeholder=""
                      mode="multiple"
                      :options="
                        reasonList.map((item) => ({
                          value: item.id,
                          label: item.name,
                        }))
                      "
                      disabled
                    >
                      <template #dropdownRender="{ menuNode: menu }">
                        <v-nodes :vnodes="menu" />
                        <a-divider style="margin: 4px 0" />
                        <div
                          style="
                            padding: 4px 8px;
                            cursor: pointer;
                            color: #1890ff;
                            text-align: center;
                          "
                          @mousedown="(e) => e.preventDefault()"
                          @click="() => (editVisible = true)"
                        >
                          添加
                        </div>
                      </template>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    label="计费天数"
                    v-bind="validateInfos.charge_days"
                  >
                    <a-input-number
                      id="inputNumber"
                      v-model:value="modelRef.charge_days"
                      :min="0"
                      style="width: 100%"
                      disabled
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-card>
        </a-col>
        <a-col :span="12" class="mt-10">
          <a-card size="small" title="房源信息">
            <checked-build
              :content="buildBindInfo"
              :height="258"
              style="overflow-y: scroll"
            />
          </a-card>
        </a-col>
      </a-row> -->
      <a-row :gutter="12" v-if="isPurposeChangeContract">
        <a-col :span="24" class="mt-10">
          <a-card size="small" class="bill-card">
            <template #title>
              <span>{{purposeData[0]?.cost_type_txt || '租赁意向保证金'}}</span>
            </template>

            <a-table
              :columns="purposeColumns"
              :data-source="purposeData"
              :loading="purposeLoading"
              :pagination="false"
              rowKey="bill_id"
            >
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'return_date'">
                  <a-date-picker
                    v-model:value="record.return_date"
                    format="YYYY-MM-DD"
                    valueFormat="YYYY-MM-DD"
                    :allowClear="false"
                  />
                </template>
                <template v-if="column.key === 'carry_over'">
                  <a-tag color="green">入</a-tag>￥{{ record.into_amount || 0 }}
                  <span v-if="record.out_amount">
                     <a-tag color="red" style="margin-left: 8px">出</a-tag>￥{{ record.out_amount || 0 }}
                  </span>
                </template>
              </template>
            </a-table>
            <a-alert
              :message="'合计应退' + Math.abs(purposeTotal).toFixed(2) + '元'"
              type="info"
            />
          </a-card>
        </a-col>
      </a-row>
      <a-row :gutter="12" v-if="!isPurposeChangeContract">
        <a-col :span="24" class="mt-10">
          <a-card size="small" class="bill-card">
            <template #title>
              <span>账单结算</span>
              <text-tip
                :tips="[
                  '退租后的账单将自动关闭，计费周期外的已结清账单不在此处显示',
                ]"
              />
            </template>

            <a-table
              :columns="billColumns"
              :data-source="billData"
              :loading="billLoading"
              :pagination="false"
              rowKey="id"
            >
              <template #headerCell="{ title, column }">
                <!-- 浏览模式下不展示tip提示 -->
                <template v-if="column.key === 'receivable_payment'">
                  <span> 应收付金额/原始应收付 </span>
                  <text-tip
                    :tips="[
                      '已按租赁天数自动计算未满计费周期的账单，修改应收/付金额视作账单调整',
                    ]"
                  />
                </template>
                <template v-if="column.key === 'receivable_payment_date'">
                  <span> 应收/付日期 </span>
                  <text-tip
                    :tips="[
                      '更改应付日期影响到滞纳金计算，请妥善操作；当涉及退款时，请合理设置应收/付日期',
                    ]"
                  />
                </template>
              </template>

              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'cost_type_txt'">
                  <span>{{ text }}</span>
                  <DeleteOutlined
                    v-if="record.is_append"
                    style="margin-left: 5px"
                    @click="deleteAppendRecord(index)"
                  />
                  <text-tip
                    :tips="['当前账单已具发票/收据，请谨慎调整账单价格']"
                    :iconType="'exclamation'"
                    v-else-if="record.issue_flag"
                  />
                </template>
                <template v-if="column.key === 'receivable_payment'">
                  <a-input-number
                    id="inputNumber"
                    v-model:value="record.receivable_payment"
                    :min="0"
                    :precision="2"
                    style="width: 55%"
                    @change="onReceivableInput(record)"
                    :disabled="record.is_append"
                  />
                  <span style="width: 45%">
                    {{`/${record.pre_receivable_payment}`}}
                  </span>
                </template>
                <template v-if="column.key === 'bill_type_txt'">
                  <a-tag color="green" v-if="record.bill_type == 1">收款</a-tag>
                  <a-tag color="orange" v-else>付款</a-tag>
                </template>
                <template v-if="column.key === 'actual_retreat'">
                  <a-tag color="green" v-if="record.pay_type === 'income'">收</a-tag>
                  <a-tag color="orange" v-else>付</a-tag>
                  <span>{{ text }}</span>
                </template>
                <template v-if="column.key === 'actual_payment'">
                  <span>{{
                    record.actual_payment ? record.actual_payment : "0.00"
                  }}</span>
                </template>
                <template v-if="column.key === 'receivable_payment_date'">
                  <a-date-picker
                    v-model:value="record.receivable_payment_date"
                    format="YYYY-MM-DD"
                    valueFormat="YYYY-MM-DD"
                  />
                </template>
                <template v-if="column.key === 'carry_over'">
                  <a-tag color="green">入</a-tag>￥{{ record.into_amount || 0 }}
                  <a-tag color="red" style="margin-left: 8px">出</a-tag>￥{{ record.out_amount || 0 }}
                </template>
              </template>
            </a-table>
            <a-alert
              :message="billTotalStatus + Math.abs(billTotal).toFixed(2) + '元'"
              type="info"
            />
          </a-card>
        </a-col>
      </a-row>
      <a-row :gutter="12" class="mt-20" v-if="!isPurposeChangeContract">
        <a-col :span="24">
          <a-card size="small" title="保证金" class="bill-card">
            <a-table
              :columns="bondColumns"
              :data-source="bondData"
              :loading="bondLoading"
              :pagination="false"
              rowKey="id"
            >
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'receivable_payment_date'">
                  <a-date-picker
                    v-model:value="record.receivable_payment_date"
                    format="YYYY-MM-DD"
                    valueFormat="YYYY-MM-DD"
                  />
                </template>
                <template v-if="column.key === 'carry_over'">
                  <a-tag color="green">入</a-tag>￥{{ record.into_amount || 0 }}
                  <a-tag color="red" style="margin-left: 8px">出</a-tag>￥{{ record.out_amount || 0 }}
                </template>
              </template>
            </a-table>
            <a-alert
              :message="bondTotalStatus + Math.abs(bondTotal).toFixed(2) + '元'"
              type="info"
            />
          </a-card>
        </a-col>
      </a-row>
      <a-row :gutter="12" v-if="!isPurposeChangeContract">
        <a-col
          :span="24"
          class="mt-20"
          style="display: flex; align-items: center; justify-content: flex-end"
        >
          <InfoCircleFilled style="font-size: 16px; color: #2681f3" />
          <div style="margin-left: 10px">
            <span>
              {{ summaryTotalStatus }}
            </span>
            <span style="margin-left: 5px; margin-right: 5px">
              {{ Math.abs(summaryTotal).toFixed(2) }}
            </span>
            元
          </div>
        </a-col>
      </a-row>
    </section>
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  watch,
  h,
  computed,
  createVNode,
  reactive,
  toRefs,
} from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate } from "vue-router";
import store from "../../../store";
import request from "../../../common/utils/request";
import moment from "moment";
import { TextTip } from "bl-common-vue3";
import {
  InfoCircleFilled,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { Modal } from "ant-design-vue";
import { Form, message } from "ant-design-vue";
import utils from "@/common/utils/utils";
import _ from "lodash";
const useForm = Form.useForm;

export default defineComponent({
  name: "newRetreat",
  components: {
    TextTip,
    // CheckedBuild,
    // VNodes: (_, { attrs }) => {
    //   return attrs.vnodes;
    // },
    InfoCircleFilled,
    DeleteOutlined,
  },
  props: {
    trigger: {
      type: Number,
      default: 0,
    },
    changeType: {
      type: String,
      default: "",
    },
    changeDetail: {
      type: Object,
      default: () => {},
    }
  },
  setup(props, context) {
    const $router = useRouter();
    const $route = useRoute();
    const id = ref(Number($route.query.id));
    const ownerId = ref(Number($route.query.owner_id));

    const billColumns = ref([]);

    const isPurposeChangeContract = computed(() => props.changeType == "purpose_change");

    const state = reactive({
      purposeData: [],
      purposeLoading: false,
      purposeTotal: 0,
    });

    const bondColumns = [
      {
        title: "费用类型",
        dataIndex: "cost_type_txt",
        width: "8%",
      },
      {
        title: "计费周期",
        customRender: ({ text, record, index }) => {
          return record.start_date + " ~ " + record.end_date;
        },
        width: "14%",
      },
      {
        title: "账单金额",
        dataIndex: "bill_amount",
        width: "10%",
      },
      {
        title: "需付金额",
        dataIndex: "actual_retreat",
        width: "12%",
      },
      {
        title: "实收金额",
        dataIndex: "actual_payment",
        width: "12%",
      },
      {
        title: "结转",
        dataIndex: "carry_over",
        key: "carry_over",
        width: "14%",
      },
      {
        title: "应退金额",
        dataIndex: "receivable_payment",
        width: "15%",
      },
      {
        title: "应退日期",
        dataIndex: "receivable_payment_date",
        key: "receivable_payment_date",
        width: "15%",
      },
    ];

    billColumns.value = [
      {
        title: "费用类型",
        dataIndex: "cost_type_txt",
        key: "cost_type_txt",
        width: "8%",
      },
      {
        title: "计费周期",
        customRender: ({ text, record, index }) => {
          return record.start_date + " ~ " + record.end_date;
        },
        width: "14%",
      },
      {
        dataIndex: "receivable_payment",
        key: "receivable_payment",
        width: "15%",
      },
      {
        title: "实收/付金额",
        dataIndex: "actual_payment",
        key: "actual_payment",
        width: "12%",
      },
      {
        title: "结转",
        dataIndex: "carry_over",
        key: "carry_over",
        width: "14%",
      },
      {
        title: "调整",
        dataIndex: "adjust_amount",
        key: "adjust_amount",
        width: "9%",
        customRender: ({ text, record, index }) => {
          return text || "--";
        },
      },
      {
        title: "需收/付金额",
        dataIndex: "actual_retreat",
        key: "actual_retreat",
        width: "14%",
      },
      {
        dataIndex: "receivable_payment_date",
        key: "receivable_payment_date",
        width: "14%",
      },
    ];

    const mainInfo = ref({});
    const buildBindInfo = ref({});
    const retreatTypeList = ref([]);
    const timeoutDay = ref(0);
    const billIds = ref([]);
    const bondIds = ref([]);
    const getBasicInfo = () => {
      request
        .get("/org", "/contract/retreatInfo", {
          contract_id: id.value,
        })
        .then((res) => {
          mainInfo.value = res.info.mainInfo;
          buildBindInfo.value = res.info.mainInfo.build_bind;
          retreatTypeList.value = res.info.retreatInfo.retreatType;
          timeoutDay.value = res.info.timeoutDay;
          const changeData = props.changeDetail;
          if (changeData) {
            if (changeData.changeContractTime) {
              modelRef.retreatDate = moment(changeData.changeContractTime)
                .subtract(1, "days")
                .format("YYYY-MM-DD");
            } else {
              modelRef.retreatDate = moment()
                .subtract(1, "days")
                .format("YYYY-MM-DD");
            }
            if (res.info && res.info.mainInfo) {
              let contract_begin_time = moment();
              if (res.info.mainInfo.lease_starttime) {
                contract_begin_time = moment(res.info.mainInfo.lease_starttime);
              }
              modelRef.charge_days = moment(modelRef.retreatDate).diff(
                contract_begin_time,
                "day"
              );
            }
          }
        })
        .finally(() => {
          getBillData(billIds.value);
          getBondData(bondIds.value);
        });
    };

    const reasonList = ref([]);
    const getReasonList = () => {
      request
        .get("/org", "/manage/taglib/termination", {
          page: 1,
          pageSize: 99,
        })
        .then((res) => {
          reasonList.value = res.list;
        });
    };

    const editVisible = ref(false);
    const addBillVisible = ref(false);

    const editTagClose = () => {
      editVisible.value = false;
    };

    const editSuccess = () => {
      editTagClose();
      getReasonList();
    };

    const addBillClose = () => {
      addBillVisible.value = false;
    };

    const addBillType = ref(1);
    const showBillModal1 = () => {
      addBillType.value = 1;
      addBillVisible.value = true;
    };

    const showBillModal2 = () => {
      addBillType.value = 2;
      addBillVisible.value = true;
    };

    const modelRef = reactive({
      retreatType: "5",
      retreatDate: moment().format("YYYY-MM-DD"),
      addressChangeDate: "",
      signDate: moment().format("YYYY-MM-DD"),
      retreatReason: [],
      charge_days: 0,
    });

    const rulesRef = reactive({
      retreatType: [{ required: false, message: "标签名称为必填项" }],
      retreatDate: [{ required: false, message: "标签名称为必填项" }],
      addressChangeDate: [{ required: false, message: "标签名称为必填项" }],
      signDate: [{ required: false, message: "标签名称为必填项" }],
      retreatReason: [{ required: false, message: "标签名称为必填项" }],
      charge_days: [{ required: false, message: "标签名称为必填项" }],
    });

    const { validate, validateInfos } = useForm(modelRef, rulesRef);

    const endOpen = ref(false);
    const signDate = computed(() => {
      return modelRef.signDate;
    });
    // const disabledStartDate = (signDate) => {
    //   if (!signDate || !modelRef.retreatDate) {
    //     return false;
    //   }
    //   //协议签订日期不能在退租日期之后，但可以在当天，时间戳+1天（一天=86400000）
    //   let startDate = "";
    //   if (modelRef.retreatDate._isAMomentObject) {
    //     if (modelRef.retreatDate.valueOf() < Date.now()) {
    //       startDate = modelRef.retreatDate.valueOf() + 86400000;
    //     } else {
    //       startDate = modelRef.retreatDate.valueOf();
    //     }
    //   } else {
    //     startDate = Date.now();
    //   }
    //   return signDate.valueOf() > startDate;
    // };

    const disabledStartDate = (current) => {
      return current > moment(modelRef.retreatDate).endOf("days");
    };

    const handleRetreatDateOpenChange = (open) => {
      endOpen.value = open;
      console.log("openopenopen", modelRef.retreatDate, modelRef.signDate);
    };

    const handleRetreatDateChange = (date, dateString) => {
      console.log("dateString", dateString);
      // 签订日期必须在退租日期之前
      if (
        !dateString ||
        (dateString &&
          modelRef.signDate &&
          new Date(dateString) < new Date(modelRef.signDate))
      ) {
        modelRef.signDate = "";
      }
      if (dateString) {
        request
          .post("/org", "/create/getRetreatBill", {
            contract_id: id.value,
            retreat_date: dateString,
          })
          .then((res) => {
            // 处理list每一条的应收付金额
            res.list.map((item) => {
              item.receivable_payment_date = moment(
                item.receivable_payment_date
              );
              item.pre_receivable_payment = item.receivable_payment;
              // 如果退租日期在账单开始日期之前，则为0
              if (minusDate(modelRef.retreatDate, item.start_date) < 0) {
                item.receivable_payment = 0;
              } else if (minusDate(modelRef.retreatDate, item.end_date) >= 0) {
                // 如果退租日期在账单开始日期之后，不计算，展示原始数据
              } else {
                // 如果退租日期在账单开始日期到结束之间，公式计算
                item.receivable_payment = calcReceivedMoney(item);
              }
              onReceivableInput(item);
            });
            billData.value = res.list;
          });
      } else {
        billData.value = [];
      }
    };

    watch(signDate, () => {
      console.log("signDate", signDate.value);
    });
    watch(
      () => modelRef.retreatDate,
      () => {
        console.log("retreatDate", modelRef.retreatDate);
      }
    );

    const billTotalStatus = computed(() => {
      if (billTotal.value >= 0) {
        return "合计需收：";
      } else {
        return "合计需付：";
      }
    });
    const billTotal = computed(() => {
      let tmpTotal = 0;
      billData.value.map((item, index) => {
        item.actual_payment = item.actual_payment || "0.00";
        let tmp = 0;
        let actualAmount = utils.countSum([
          Number(item.actual_payment),
          Number(item.into_amount),
          -Number(item?.out_amount || 0),
        ]);
        tmp = utils.countSum([
          Number(item.receivable_payment),
          -Number(actualAmount),
        ]);
        if (
          item.pay_type == 'pay' &&
          tmp >= 0
        ) {
          tmp = utils.countSum([
            0,
            -Number(tmp),
          ]);
        }
        tmpTotal = utils.countSum([tmpTotal, tmp]);
      });
      return tmpTotal;
    });

    const bondTotalStatus = computed(() => {
      if (bondTotal.value >= 0) {
        return "合计需收：";
      } else {
        return "合计需付：";
      }
    });

    const bondTotal = computed(() => {
      let tmpTotal = 0;
      bondData.value.map((item, index) => {
        tmpTotal = utils.countSum([tmpTotal, -Number(item.receivable_payment)]);
      });
      return tmpTotal;
    });

    const summaryTotal = computed(() => {
      return utils.countSum([billTotal.value, bondTotal.value]);
    });

    const summaryTotalStatus = computed(() => {
      if (summaryTotal.value >= 0) {
        return "合计需收：";
      } else {
        return "合计需付：";
      }
    });

    const billData = ref([]);
    const billLoading = ref(false);
    const bondData = ref([]);
    const bondLoading = ref(false);

    const getBillData = (billIds) => {
      billLoading.value = true;
      let params = {
        contract_id: id.value,
        retreat_date: moment().format("YYYY-MM-DD"),
        agreeBill: billIds || [],
      };
      const changeData = props.changeDetail;
      if (changeData && changeData.changeContractTime) {
        params.retreat_date = moment(changeData.changeContractTime)
          .subtract(1, "days")
          .format("YYYY-MM-DD");
      }
      request.post("/org", "/create/getRetreatBill", params).then((res) => {
        // 处理list每一条的应收付金额
        res.list.map((item) => {
          // 如果退租日期在账单开始日期之前，则为0
          item.pre_receivable_payment = item.receivable_payment;
          if (minusDate(modelRef.retreatDate, item.start_date) < 0) {
            item.receivable_payment = "0.00";
          } else if (minusDate(modelRef.retreatDate, item.end_date) >= 0) {
            // 如果退租日期在账单开始日期之后，不计算，展示原始数据
          } else {
            // 如果退租日期在账单开始日期到结束之间，公式计算
            item.receivable_payment = calcReceivedMoney(item);
          }
          onReceivableInput(item);
        });
        billData.value = res.list;
        billLoading.value = false;
      });
    };
    const getBondData = (bondIds) => {
      bondLoading.value = true;
      request
        .post("/org", "/create/getRetreatBond", {
          contract_id: id.value,
          agreeBond: bondIds || [],
        })
        .then((res) => {
          if (res.list.length > 0) {
            res.list.map((item) => {
              item.actual_payment = item.actual_payment || "0.00"; // 实收金额(多少就是多少)
              item.actual_retreat = utils.countSum([Number(item.actual_payment), Number(item.into_amount || 0), -Number(item.out_amount || 0)]) //  需付金额 = 实收金额 + 转入金额 - 转出金额
              item.receivable_payment = item.actual_retreat || "0.00"; //  需付
              item.bill_type = 2;
            });
          }
          bondData.value = res.list;
          bondLoading.value = false;
        });
    };

    // 计算【账单】每一项的应收付金额
    // 公式：原账单应收付金额×【（退租日期-计租开始日期+1)/(计租结束日期-计租开始日期+1）】
    const minusDate = (date1, date2) => {
      return moment(new Date(date1)).diff(new Date(date2), "day");
    };

    const calcReceivedMoney = (record) => {
      let percent =
        (minusDate(modelRef.retreatDate, record.start_date) + 1) /
        (minusDate(record.end_date, record.start_date) + 1);
      let money = (Number(record.receivable_payment) * percent).toFixed(2);
      return money;
    };

    const getPurposeData = () => {
      state.purposeLoading = true;
      request
        .get("/org", "/contract/change/getPurposseBill", {
          contract_id: id.value,
        })
        .then((res) => {
          // 需付金额
          (res?.bill_info || []).map((item) => {
            item.actual_retreat = utils.countSum([Number(item.actual_payment), Number(item.into_amount || 0), -Number(item.out_amount || 0)]); //  需付金额 = 实收金额 + 转入金额 - 转出金额
            item.actual_retreat = Number(item.actual_retreat).toFixed(2);
            item.return_date = item.return_date || moment().format("YYYY-MM-DD");
          })
          state.purposeData = res?.bill_info || [];
          state.purposeTotal = state.purposeData.reduce((acc, cur) => utils.countSum([acc, Number(cur.actual_retreat)]), 0);
        }).finally(() => {
        state.purposeLoading = false;
      });
    };

    const init = () => {
      if (isPurposeChangeContract.value) {
        // 意向合同变更结算
        getPurposeData();
      } else {
        if (id.value) {
          getBasicInfo();
          getReasonList();
        }
      }
    };

    const onReceivableInput = (record) => {
      // 需收 = 应收-（实收-转出+转入）
      // 实收-转出+转入
      let actualAmount = utils.countSum([
        Number(record.actual_payment),
        Number(record.into_amount),
        -Number(record?.out_amount || 0),
      ]);
      let amount = utils.countSum([
        Number(record.receivable_payment),
        -Number(actualAmount),
      ]);
      record.actual_retreat = Math.abs(amount)
        .toFixed(2)
        .toString();
      if (
        amount >=
        0
      ) {
        record.pay_type = 'income';
      } else {
        record.pay_type = 'pay';
      }
    };

    const deleteAppendRecord = (index) => {
      Modal.confirm({
        title: "确认删除吗？",
        icon: createVNode(ExclamationCircleOutlined),
        content: "",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          billData.value.splice(index, 1);
        },
      });
    };

    const validateForm = () => {
      let params = {};
      if (isPurposeChangeContract.value) {
        params = {
          purpose_bill: state.purposeData,
        };
      } else {
        params = {
          bill_info: billData.value,
          bond_info: bondData.value,
          total_cost: {
            billReceivable: billTotal.value,
            bondReceivable: bondTotal.value,
            receivableTotal: summaryTotal.value,
          },
        };
      }
      console.log(params);
      store.dispatch("SetAddFormData", {
        key: "settleInfo",
        data: params,
      });
      context.emit("success");
    };

    watch(
      () => props.trigger,
      (val) => {
        if (val) {
          validateForm();
        }
      }
    );

    let initFlag = ref(true);
    watch(
      () => store.getters.currentStep,
      (val) => {
        if (val == 3 && initFlag.value) {
          init();
          initFlag.value = false;
        }
      }
    );

    return {
      ...toRefs(state),
      addBillVisible,
      editVisible,
      mainInfo,
      buildBindInfo,
      retreatTypeList,
      reasonList,
      timeoutDay,
      editTagClose,
      editSuccess,

      endOpen,
      disabledStartDate,
      handleRetreatDateOpenChange,
      handleRetreatDateChange,

      billColumns,
      billData,
      billLoading,
      bondColumns,
      bondData,
      bondLoading,

      addBillClose,
      showBillModal1,
      showBillModal2,
      addBillType,
      id,
      billTotal,
      bondTotal,
      summaryTotal,
      ownerId,

      billTotalStatus,
      summaryTotalStatus,

      validateInfos,
      modelRef,
      bondTotalStatus,
      onReceivableInput,
      deleteAppendRecord,
      isPurposeChangeContract,
      purposeColumns,
    };
  },
});

const purposeColumns = [
  {
    title: "费用类型",
    dataIndex: "cost_type_txt",
    key: "cost_type_txt",
    width: "8%",
  },
  {
    title: "计费周期",
    dataIndex: "contractOn",
    key: "contractOn",
    width: "14%",
  },
  {
    title: "账单金额",
    dataIndex: "bill_amount",
    key: "bill_amount",
    width: "14%",
  },
  {
    title: "需付金额",
    dataIndex: "actual_retreat",
    key: "actual_retreat",
    width: "12%",
  },
  {
    title: "实收金额",
    dataIndex: "actual_payment",
    key: "actual_payment",
    width: "12%",
  },
  {
    title: "结转",
    dataIndex: "carry_over",
    key: "carry_over",
    width: "14%",
  },
  {
    title: "应退金额",
    dataIndex: "actual_retreat",
    key: "actual_retreat",
    width: "12%",
  },
  {
    title: "应退日期",
    dataIndex: "return_date",
    key: "return_date",
    width: "14%",
  },
]
</script>

<style lang="less" scoped>
.new-retreat {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    background-color: #fff;

    :deep(.ant-list-item-meta-avatar) {
      margin-right: 32px;
      margin-left: 16px;
      margin-top: 10px;
    }

    :deep(.ant-page-header) {
      padding-bottom: 0;
    }
  }

  .content {
    flex: 1;
    width: 100%;
    max-height: calc(100% - 210px);
    padding: 10px;
    box-sizing: border-box;
    overflow-y: auto;
    overflow-x: auto;

    .bill-card {
      :deep(.ant-alert-info) {
        background-color: #fafafa;
        border: none;
      }

      :deep(.ant-alert-message) {
        text-align: right;
        padding-right: 10px;
      }
    }
  }

  #footer {
    :deep(.ant-page-header) {
      padding-bottom: 20px;
    }
  }
}
</style>
